package com.shiguiwu.springmybatis.leetcode;

/**
 * @description:
 * @author: stone
 * @date: Created by 2022/7/31 23:02
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.leetcode
 */

import java.util.LinkedList;
import java.util.Queue;

/**
 * Definition for a binary tree node.
 **/
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }


    /**
     * 给你一个二叉树的根节点 root。设根节点位于二叉树的第 1 层，而根节点的子节点位于第 2 层，依此类推。
     * <p>
     * 请返回层内元素之和 最大 的那几层（可能只有一层）的层号，并返回其中 最小 的那个。
     *
     * @param root
     * @return
     */
    public int maxLevelSum(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return 0;
        }
        queue.offer(root);
        int num = 1;
        //用于维护层序之和，以及层序序号,
        int[] res = new int[]{Integer.MIN_VALUE, 1};
        while (!queue.isEmpty()) {
            int sum = 0;
            int len = queue.size();
            for (int i = 0; i < len; i++) {
                TreeNode tmp = queue.poll();
                sum += tmp.val;
                if (tmp.left != null) {
                    queue.offer(tmp.left);
                }
                if (tmp.right != null) {
                    queue.offer(tmp.right);
                }
            }
            if (res[0] < sum) {
                res[0] = sum;
                res[1] = num;
            }
            num++;
        }
        return res[1];
    }


    int sum;
    int max;
    /**
     * 给你一棵二叉树的根节点 root ，请你返回 层数最深的叶子节点的和 。
     * @param root
     * @return
     */
    public int deepestLeavesSum(TreeNode root) {
        find(root, 0);
        return sum;
    }

    public void find(TreeNode root, int level) {
        if (root == null) {
            return;
        }
        if (level > max) {
            max = level;
            sum = root.val;
        } else if (level == max) {
            sum += root.val;
        }
        find(root.left, level + 1);
        find(root.right, level + 1);
    }
}
